package com.xyy.jd_clund.utils;

import com.kingdee.service.ApiException;
import com.kingdee.service.data.api.SystemApi;
import com.kingdee.service.data.entity.AreaLoadRes;
import com.kingdee.service.data.entity.CityLoadRes;
import com.kingdee.service.data.entity.DivisionLoadReply;
import com.kingdee.service.data.entity.DivisionLoadRes;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public class LocationHelper {
    static List<DivisionLoadRes> jsonData;

    //初始化
    static {
        if (jsonData.isEmpty() && jsonData.size() <= 0) {
            SystemApi systemApi = new SystemApi();
            DivisionLoadReply divisionLoadReply = null;
            try {
                divisionLoadReply = systemApi.systemDivisionLoad(null);
                jsonData = divisionLoadReply.getRows();
            } catch (ApiException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //传入省名称获取省id
    @Nullable
    public static String getProvinceId(String province) {
        for (DivisionLoadRes provinceObj : jsonData) {
            if (province.equals(provinceObj.getName())) {
                return provinceObj.getId();
            }
        }
        return null;
    }

    //传入省市名称获取市id
    @Nullable
    public static String getCityId(String province, String city) {
        String provinceId = getProvinceId(province);
        for (DivisionLoadRes provinceObj : jsonData) {
            if (province.equals(provinceObj.getName())) {
                for (CityLoadRes cityObj : provinceObj.getSonNodes()) {
                    if (city.equals(cityObj.getName())) {
                        return cityObj.getId();
                    }
                }
            }
        }
        return null;
    }

    // 传入省市区名称获取区id的方法
    @Nullable
    public static String getLocationId(String province, String city, String district){

        // 遍历省份
        for (DivisionLoadRes provinceObj : jsonData) {
            if (province.equals(provinceObj.getName())) {
                // 遍历城市
                for (CityLoadRes cityObj : provinceObj.getSonNodes()) {
                    if (city.equals(cityObj.getName())) {
                        // 遍历区县
                        for (AreaLoadRes districtObj : cityObj.getSonNodes()) {
                            if (district.equals(districtObj.getName())) {
                                return districtObj.getId(); // 返回匹配的id
                            }
                        }
                    }
                }
            }
        }
        return null; // 未找到匹配的id，返回null
    }

}